package com.iterative.common.util;

import java.util.HashMap;
import java.util.Map;

import javax.persistence.Table;

import org.hibernate.SessionFactory;
import org.hibernate.metadata.ClassMetadata;
import org.springframework.beans.BeansException;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;


public class ApplicationContextUtil implements ApplicationContextAware {
    private static ApplicationContext context;

    public void setApplicationContext(ApplicationContext context)
        throws BeansException {
        this.context = context;
    }

    public static ApplicationContext getContext() {
        return context;
    }
    
    
    public static Map<String, ClassMetadata> getAllClassMetadata(){
    	SessionFactory sessionFactory = (SessionFactory) context.getBean("sessionFactory");
    	return sessionFactory.getAllClassMetadata();
    }
    
    public static Map<String, String> getTables(){
    	Map<String, ClassMetadata> map = getAllClassMetadata();
    	 Map<String, String> tableMap = new HashMap<String, String>();
    	try {
    		for (String key : map.keySet()) {
        		Class<?> cls = Class.forName(key); //或直接XXXX.class
    			String name = cls.getAnnotation(Table.class).name();
    			tableMap.put(name, key);
    		}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    	return tableMap;
    	
    }
}
